/*
 * @Author: your name
 * @Date: 2021-06-03 17:16:36
 * @LastEditTime: 2021-06-04 15:57:37
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \bazai_island_api\app\api\book.js
 */
const Router = require('koa-router')
const router = new Router()

router.prefix('/v1/book')

const { HotBook } = require('@models/hot-book')
const { PositiveIntegerValidator, SearchValidator, AddShortCommentValidator } = require('@validators/validators')
const { Book } = require('@models/book')
const { Favor } = require('@models/favor')
const { Auth } = require('@middlewares/auth')
const { Comment } = require('@models/book-comment')
const { success } = require('../../lib/helper') 
router.get('/hot_list', async (ctx, next) => {
  const result = await HotBook.getAll()
    ctx.body = {
      data: result
    }
})

router.get('/:id/detail', async (ctx) => {
  const v = await new PositiveIntegerValidator().validate(ctx)
  const id = v.get('path.id')
  const book = await new Book(id)
  const result = await book.detail()
  ctx.body = {
    code: 200,
    data: result 
  }
})
// 搜索接口
router.get('/search', async (ctx) => {
  const v = await new SearchValidator().validate(ctx)
  const q = await v.get('query.q')
  const start = await v.get('query.start')
  const count = await v.get('query.count')
  const result = await Book.searchFromYuShu(q, start, count)
  ctx.body = {
    code: 200,
    data: result
  }
})

// 获取用户喜欢书籍的数量
router.get('/favor/count', new Auth().m, async (ctx) => {
  const count = await Book.getMyFavorBookCount(ctx.auth.uid)
  ctx.body = {
    code: 200,
    count
  }
})

// 获取书籍点赞情况
router.get('/:book_id/favor', new Auth().m, async(ctx) => {
  const v = await new PositiveIntegerValidator().validate(ctx, {
    id: 'book_id'
  })
  const bookId = await v.get('path.book_id')
  const favor = await Favor.getBookFavor(ctx.auth.uid, bookId)
  ctx.body = {
    code: 200,
    data: favor
  }
})

router.post('/add/short_comment', new Auth().m, async (ctx) => {
  const v = await new AddShortCommentValidator().validate(ctx, {
    id: 'book_id'
  })
  const id = v.get('body.book_id')
  const content = v.get('body.content')
  await Comment.addComment(id, content)
  success()
})

router.get('/:book_id/short_comment', new Auth().m, async (ctx) => {
  const v = await new PositiveIntegerValidator().validate(ctx, {
    id: 'book_id'
  })
  const id = v.get('path.book_id')
  const result = await Comment.getComment(id)
  ctx.body = {
    code: 200,
    data: result
  }
})

module.exports = router
